﻿using System;
using System.Web.Mvc;
using Orchard.ContentManagement.MetaData;
using Orchard.DisplayManagement;
using Orchard.Environment.Extensions;
using Orchard.Events;
using Orchard.Localization;

namespace Downplay.Audit.Rules
{
    [OrchardFeature("Downplay.Audit.Rules.Content")]
    public class ContentForms : IFormProvider {
        private readonly IContentDefinitionManager _contentDefinitionManager;
        protected dynamic Shape { get; set; }
        public Localizer T { get; set; }

        public ContentForms(
            IShapeFactory shapeFactory,
            IContentDefinitionManager contentDefinitionManager) {

            _contentDefinitionManager = contentDefinitionManager;
            Shape = shapeFactory;

            T = NullLocalizer.Instance;
        }

        public void Describe(dynamic context) {
            Func<IShapeFactory, dynamic> form =
                shape => {

                    var f = Shape.Form(
                        Id: "AnyOfContentTypesAndDisplayTypes",
                        _Parts: Shape.SelectList(
                            Id: "contenttypes", Name: "contenttypes",
                            Title: T("Content types"),
                            Description: T("Select some content types."),
                            Size: 10,
                            Multiple: true
                            ),
                        _DisplayTypes: Shape.TextBox(
                            Id: "displaytypes", Name: "displaytypes",
                            Title: T("Display types"),
                            Description: T("Comma-separated list of display types (e.g. Detail) or blank for all (will produce a lot of noise for summary views etc.)."),
                            Classes: new[] { "text" }
                            ));

                    f._Parts.Add(new SelectListItem { Value = "", Text = T("Any").Text });

                    foreach (var contentType in _contentDefinitionManager.ListTypeDefinitions()) {
                        f._Parts.Add(new SelectListItem { Value = contentType.Name, Text = contentType.DisplayName });
                    }

                    return f;
                };

            context.Form("SelectContentTypesAndDisplayTypes", form);

        }
    }
}